<template>
  <view>
    <u-sticky>
      <Navbar
        title="照片AI风格转绘"
        :height="Number(height)"
        :boundingTop="Number(boundingTop)"
      ></Navbar>
    </u-sticky>
    <view class="content-box" :style="{ marginTop: 15 + 'px' }">
      <view class="content-box-title"> 上传图片 </view>
      <view class="content-box-title1">
        上传你的图片，我会为你AI智能风格转绘照片哦~
      </view>
      <view class="content-box-title2"> (每次生成五张) </view>

      <view class="content-box-upload">
        <u-upload
          :fileList="fileList1"
          @afterRead="afterRead"
          @delete="deletePic"
          name="1"
          multiple
          :maxCount="1"
          uploadText="上传"
          width="672rpx"
          height="644rpx"
        >
          <!-- uploadIcon="https://ai.mojudianzisw.com/static/img/shop/ai/upload.png" -->
          <view
            class="u-upload-btn box-upload"
            style="width: 630rpx; height: 654rpx"
          >
            <img
              style="width: 100rpx; height: 75rpx"
              src="https://ai.mojudianzisw.com/static/img/shop/ai/upload.png"
              alt=""
            />
            <view
              class=""
              style="width: 100%; text-align: center; margin-top: 5rpx"
            >
              上传
            </view>
          </view>
        </u-upload>
      </view>

      <view
        class="content-box-button"
        @click="takePhoto"
        v-if="fileList1.length <= 0"
      >
        相机拍摄
      </view>
      <view class="content-box-button" v-else @click="openPay">
        支付5元开始绘图
      </view>
      <view
        class="content-box-button1"
        v-if="fileList1.length <= 0"
        @click="chooseImage"
      >
        从相册上传
      </view>
    </view>
    <u-popup
      :show="show"
      :round="10"
      mode="center"
      @close="close"
      @open="openPay"
    >
      <view class="popup-content">
        <view class="popup-content-img">
          <img
            style="width: 460rpx; height: 314rpx"
            src="https://ai.mojudianzisw.com/static/img/shop/ai/zfbg.png"
            alt=""
          />
        </view>
        <view class="popup-content-text"> 支付成功即可开始绘图 </view>
        <view class="popup-content-button" @click="payWechat">立即支付</view>
        <!-- $navigateTo(`/pages/creation/createimg?url=${fileList1[0].url}`) payWechat $navigateTo(`/pages/creation/createimg?url=${url}`) -->
        <view class="popup-content-nopay" @click="close">暂不支付</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import setMarginTop from "@/mixins/setMarginTop"; // 引入 mixin
import Navbar from "@/components/navbar.vue";
import { createOrder } from "@/api/index.js"; // 引入 api
export default {
  mixins: [setMarginTop], // 使用 mixin
  components: {
    Navbar,
  },
  data() {
    return {
      fileList1: [
        // {url: 'https://ai.mojudianzisw.com/static/img/shop/ai/upload.png'}
        //
      ],
      show: false,
      taskId: "",
      sum: 0,
    };
  },
  onLoad() {},
  methods: {
    ceshi() {
      uni.uploadFile({
        url: `https://ai2.mojudianzisw.com/ai/v2/face/fusion`,
        filePath: this.fileList1[0].url,
        name: "file",
        header: {},
        formData: {
          openId: uni.getStorageSync("openId"),
        },
        success: (res) => {
          console.log(res);
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },
    async payWechat() {
      const data = await createOrder({
        orderType: "HANMAN",
      });
      console.log(data);
      if (data.code == 200) {
        const that = this;
        uni.requestPayment({
          provider: "wxpay", // 支付宝 provider 使用 wxpay
          timeStamp: data.info.timeStamp, // 时间戳
          nonceStr: data.info.nonceStr, // 随机字符串
          package: data.info.packageVal, // 预支付交易会话标识
          signType: data.info.signType, // 签名方式
          paySign: data.info.paySign, // 签名
          success(res) {
            console.log("支付成功:", res);
            uni.showToast({
              title: "支付成功",
              icon: "success",
            });
            console.log("1123213", that.fileList1);
            that.uploadFilePromise(that.fileList1[0].url);
            that.show = false;
            setTimeout(() => {
                uni.navigateTo({
                  url: `/pages/creation/createimg?taskId=${data.info.taskId}&sum=${data.info.sum}`,
                });
              }, 500);
            console.log(that, this);
          },
          fail(err) {
            console.error("支付失败:", err);
            uni.showToast({
              title: "支付失败",
              icon: "none",
            });
          },
        });

        uni.setStorageSync("timeStamp", data.info.timeStamp);
        uni.setStorageSync("nonceStr", data.info.nonceStr);
        uni.setStorageSync("packageVal", data.info.packageVal);
        uni.setStorageSync("signType", data.info.signType);
        uni.setStorageSync("paySign", data.info.paySign);
      }
    },

    // 访问相册
    chooseImage() {
      // 调用uni.chooseImage API打开相册
      uni.chooseImage({
        count: 1, // 最多选择一张图片
        sizeType: ["original", "compressed"], // 可以选择原图或压缩图
        sourceType: ["album"], // 可以选择相册或拍照
        success: (res) => {
          // 获取选中的图片路径
          this.imagePath = res.tempFilePaths[0]; // 获取第一张图片的路径
          console.log("选中的图片路径:", this.imagePath);
          this.fileList1.push({
            url: this.imagePath,
            name: 1,
          });
          // this.uploadFilePromise(this.imagePath);
        },
        fail: (err) => {
          console.error("选择图片失败", err);
        },
      });
    },

    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
        });
      });
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },

    uploadFilePromise(url) {
      // const that = this;
      uni.uploadFile({
        url: "https://ai2.mojudianzisw.com/ai/v2/face/fusion", // 仅为示例，非真实的接口地址
        filePath: url, // 确保 url 是有效的文件路径
        name: "file", // 后端接收文件的字段名
        header: {
          Authorization: `Bearer ${uni.getStorageSync("token")}`, // 确保 token 存在
        },
        formData: {
          openId: uni.getStorageSync("openId"), // 确保 openId 存在
          type: "HANMAN", // 固定的类型
        },
        success: (uploadFileRes) => {
          try {
            const data = JSON.parse(uploadFileRes.data); // 确保 data 是 JSON 格式
            console.log(data);
            if (data.info) {
              uni.$emit('info', data.info);
              this.taskId = data.info.taskId;
              this.sum = data.info.sum;
            } else {
              console.error("响应数据格式不符合预期", data);
            }
          } catch (error) {
            console.error("解析返回数据出错:", error);
          }
        },
        fail: (err) => {
          console.error("上传文件失败:", err); // 上传失败时的错误处理
        },
        complete: () => {
          // 可以在这里执行一些清理操作，比如隐藏加载提示
          console.log("文件上传完成");
        },
      });
    },

    // 拍照
    takePhoto() {
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting["scope.camera"]) {
            uni.authorize({
              scope: "scope.camera",
              success: () => {
                // 授权成功，执行相机相关操作
                uni.chooseImage({
                  sourceType: ["camera"],
                  success: (chooseRes) => {
                    console.log(chooseRes);
                    this.fileList1.push({
                      url: chooseRes.tempFilePaths[0],
                      name: 1,
                    });
                  },
                });
              },
              fail: () => {
                // 授权失败，提示用户授权
                uni.showModal({
                  title: "提示",
                  content: "请授权相机权限",
                  showCancel: false,
                });
              },
            });
          } else {
            // 如果已经授权，则直接调用相机相关 API
            uni.chooseImage({
              sourceType: ["camera"],
              success: (chooseRes) => {
                console.log(chooseRes);
                this.fileList1.push({
                  url: chooseRes.tempFilePaths[0],
                  name: 1,
                });
              },
            });
          }
        },
      });
    },

    close() {
      this.show = false;
    },
    openPay() {
      this.show = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  width: 100%;
  height: auto;
  min-height: 300rpx;
  // border: 1px solid black;
  position: absolute;
  &-title {
    width: calc(100% - 120rpx);
    margin-left: 60rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #000000;
    margin-top: 10rpx;
  }
  &-title1 {
    width: calc(100% - 120rpx);
    margin-left: 60rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: #000000;
    margin-top: 10rpx;
  }
  &-title2 {
    width: calc(100% - 120rpx);
    margin-left: 60rpx;
    color: #999999;
    font-size: 28rpx;
    font-weight: 400;
  }
  &-upload {
    width: calc(100% - 120rpx);
    height: 654rpx;
    background-color: #f5f5f5;
    margin-top: 30rpx;
    margin-left: 60rpx;
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &-button {
    width: calc(100% - 64rpx);
    margin-left: 32rpx;
    height: 88rpx;
    background: #f56364;
    box-shadow: inset 0rpx 8rpx 12rpx 0rpx #ffafb0;
    border-radius: 72rpx;
    text-align: center;
    line-height: 88rpx;
    color: #fff;
    font-size: 28rpx;
    margin-top: 116rpx;
  }
  &-button1 {
    width: 686rpx;
    margin-left: 32rpx;
    height: 88rpx;
    border: 2rpx solid #f56364;
    color: #f56364;
    border-radius: 72rpx;
    text-align: center;
    font-size: 28rpx;
    line-height: 88rpx;
    margin-top: 32rpx;
  }
}
.box-upload {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-wrap: wrap;
}
.popup-content {
  width: 586rpx;
  min-height: 638rpx;
  &-img {
    width: 100%;
    height: 314rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50rpx;
  }
  &-text {
    width: 100%;
    display: flex;
    justify-content: center;
    color: #333333;
    font-size: 32rpx;
    font-weight: 400;
    margin-top: 28rpx;
  }
  &-button {
    width: calc(100% - 72rpx);
    height: 90rpx;
    border-radius: 180rpx;
    background: #f56364;
    box-shadow: inset 0rpx 8rpx 12rpx 0rpx #ffafb0;
    text-align: center;
    line-height: 90rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    margin: 0 36rpx;
    margin-top: 54rpx;
  }
  &-nopay {
    width: 100%;
    text-align: center;
    font-weight: 500;
    font-size: 32rpx;
    color: #f56364;
    margin-top: 38rpx;
    padding-bottom: 20rpx;
  }
}
</style>
